package com.coincalf.task.event;

import com.alibaba.fastjson.JSONObject;
import com.coincalf.chan.feign.MessagingServiceClient;
import com.coincalf.framework.enums.KlineType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * 每5秒推送K线数据
 *
 * @author qiang
 */
@Slf4j
@Component
public class KlineEvent implements Runnable {

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        KlineEvent.redisTemplate = redisTemplate;
    }

    private static RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public void setMessagingTemplate(MessagingServiceClient messagingServiceClient) {
        KlineEvent.messagingServiceClient = messagingServiceClient;
    }

    private static MessagingServiceClient messagingServiceClient;

    /**
     * 交易对标识符
     */
    private String symbol;

    /**
     * 通道
     */
    private String channel;

    /**
     * redis key 前缀
     */
    private String keyPrefix;

    public KlineEvent() {
    }

    public KlineEvent(String symbol, String channel, String keyPrefix) {
        this.symbol = symbol;
        this.channel = channel;
        this.keyPrefix = keyPrefix;
    }

    @Override
    public void run() {
        for (KlineType klineType : KlineType.values()) {
            if (klineType == KlineType.ONE_SECONDS || klineType == KlineType.FIVE_SECONDS) {
                continue;
            }
            String group = String.format(channel, symbol.toLowerCase(), klineType.getValue()).toLowerCase();
            String key = new StringBuffer(keyPrefix).append(symbol).append(":").append(klineType.getValue()).toString();
            List<Object> klines = redisTemplate.opsForList().range(key, 0, 999);
            if (!CollectionUtils.isEmpty(klines)) {
                Collections.reverse(klines);
                JSONObject body = new JSONObject();
                body.put("tick", klines);
                //group -> market.btcusdt.kline.1hour
                //body.toJSONString() -> {"tick":[[1609149600000,19186.24,19186.24,19186.24,19186.24,0.0]]}
                messagingServiceClient.convertAndSendToGroup(group, body.toJSONString());
            }
        }
    }

}
